const axios = require('axios')
// import store from '../store'
import { getToken } from '@/utils/auth'
const TIME_OUT = 3600 * 1000
// axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? '' : window.location.origin

function getError(action, option, xhr) {
  var msg = void 0
  if (xhr.response) {
    msg = '' + (xhr.response.error || xhr.response)
  } else if (xhr.responseText) {
    msg = '' + xhr.responseText
  } else {
    msg = 'fail to post ' + action + ' ' + xhr.status
  }

  var err = new Error(msg)
  err.status = xhr.status
  err.method = 'post'
  err.url = action
  return err
}

function getBody(xhr) {
  var text = xhr.responseText || xhr.response
  if (!text) {
    return text
  }

  try {
    return JSON.parse(text)
  } catch (e) {
    return text
  }
}

function uploadFileByElementUI(option, loader) {
  if (typeof XMLHttpRequest === 'undefined') {
    return
  }
  const xhr = new XMLHttpRequest()
  const action = option.action
  const formData = new FormData()
  if (option.data) {
    Object.keys(option.data).forEach(function(key) {
      const value = option.data[key]
      if (Array.isArray(value)) {
        value.forEach(single => {
          formData.append(key, single)
        })
      } else {
        formData.append(key, option.data[key])
      }
    })
  }
  if (option.files) {
    const fileKeys = Object.keys(option.files)
    fileKeys.forEach((fileKey) => {
      // if (option.files[fileKey]) {
      formData.append(fileKey, option.files[fileKey])
      // }
    })
  } else if (option.filename && option.file) {
    formData.append(option.filename, option.file)
  }

  xhr.onerror = function error(e) {
    const err = getError(action, option, xhr)
    option.onError(err)
    if (!err.stopPropagation) {
      loader.fileErrorHandler(e)
    }
  }
  xhr.onload = function onload() {
    if (xhr.status < 200 || xhr.status >= 300) {
      const err = getError(action, option, xhr)
      option.onError(err)
      if (!err.stopPropagation) {
        loader.fileErrorHandler(err)
      }
      return
    }

    const res = getBody(xhr)
    const Response = res.Response || {}

    if (!Response.Error) {
      option.onSuccess(Response)
    } else {
      const err = getError(action, option, xhr)
      option.onError(err)
      if (!err.stopPropagation) {
        loader.fileErrorHandler(Response.Error)
      }
    }
  }
  xhr.open('post', action, true)

  if (option.withCredentials && 'withCredentials' in xhr) {
    xhr.withCredentials = true
  }

  const headers = option.headers || {}
  const username = getToken()
  if (username) {
    headers['username'] = username
  }
  // if (process.env.NODE_ENV === 'development') {
  //   const username = localStorage.getItem('username')
  //   if (username) {
  //     headers['username'] = username
  //   } else {
  //     headers['username'] = 'admin' // TODO: 之后要删掉
  //   }
  // } else {
  //   headers['X-TC-Action'] = option.data.Action
  //   headers['X-TC-Region'] = 'ap-guangzhou'
  //   headers['X-TC-Timestamp'] = Math.round(new Date().getTime() / 1000).toString()
  //   headers['X-TC-Service'] = 'AMTPGate'
  //   headers['X-TC-Version'] = '2020-05-14'
  // }

  for (const item in headers) {
    // eslint-disable-next-line no-prototype-builtins
    if (headers.hasOwnProperty(item) && headers[item] !== null) {
      xhr.setRequestHeader(item, headers[item])
    }
  }
  // 获取进度条
  if (xhr.upload) {
    xhr.upload.onprogress = function progress(e) {
      if (e.total > 0) {
        e.percent = (e.loaded / e.total) * 100
      }
      option.onProgress(e)
    }
  }
  if (xhr.custom) {
    xhr.custom.xhr.upload.onprogress = function progress(e) {
      if (e.total > 0) {
        e.percent = (e.loaded / e.total) * 100
      }
      option.onProgress(e)
    }
  }
  xhr.send(formData)
  return xhr
}

const loader = {
  beforeRequest: () => {
    return null
  },
  errorHandler: () => {},
  fileErrorHandler: () => {},

  post: function(url, data, customError, timeout) {
    return new Promise((resolve, reject) => {
      const result = this.beforeRequest()
      if (result != null) {
        reject(result)
        return
      }
      if (!data) {
        data = {}
      }
      const headers = {
        'content-type': 'application/json'
      }
      const username = getToken()
      if (username) {
        headers['username'] = username
      }
      // if (process.env.NODE_ENV === 'development') {
      //   const username = localStorage.getItem('username')
      //   if (username) {
      //     headers['username'] = username
      //   } else {
      //     headers['username'] = 'admin' // TODO: 之后要删掉
      //   }
      // } else {
      //   headers['X-TC-Action'] = data.Action
      //   headers['X-TC-Region'] = 'ap-guangzhou'
      //   headers['X-TC-Timestamp'] = Math.round(new Date().getTime() / 1000).toString()
      //   headers['X-TC-Service'] = 'AMTPGate'
      //   headers['X-TC-Version'] = '2020-05-14'
      // }
      axios({
        method: 'POST',
        url: url,
        baseURL: window.location.origin,
        responseType: 'json',
        timeout: timeout || TIME_OUT,
        data: JSON.stringify(data),
        headers
      }).then(function(data) {
        data = data && data.data && data.data.Response || {}
        if (data.code === 200) {
          resolve(data)
          return
        }
        if (customError) {
          reject(data)
        } else {
          const err = data
          loader.errorHandler(err)
          reject(err)
        }
      }).catch(function(data) {
        if (customError) {
          reject()
        } else {
          loader.errorHandler(data)
          reject(data)
        }
      })
    })
  },

  get: function(url, data, customError) {
    return new Promise((resolve, reject) => {
      const result = this.beforeRequest()
      if (result != null) {
        reject(result)
        return
      }
      if (!data) {
        data = {}
      }
      const headers = {}
      const username = getToken()
      if (username) {
        headers['username'] = username
      }
      // if (process.env.NODE_ENV === 'development') {
      //   const username = localStorage.getItem('username')
      //   if (username) {
      //     headers['username'] = username
      //   } else {
      //     headers['username'] = 'admin' // TODO: 之后要删掉
      //   }
      // } else {
      //   headers['X-TC-Action'] = data.Action
      //   headers['X-TC-Region'] = 'ap-guangzhou'
      //   headers['X-TC-Timestamp'] = Math.round(new Date().getTime() / 1000).toString()
      //   headers['X-TC-Service'] = 'DeliveryServer'
      //   headers['X-TC-Version'] = '2020-05-21'
      // }
      axios({
        method: 'get',
        url: url,
        baseURL: window.location.origin,
        timeout: TIME_OUT,
        params: data,
        headers
      }).then(function(data) {
        data = data && data.data && data.data.Response || {}
        if (data.code === 200) {
          resolve(data)
          return
        }
        if (customError) {
          reject(data)
        } else {
          const err = data
          loader.errorHandler(err)
          reject(err)
        }
      }).catch(function(data) {
        if (customError) {
          reject()
        } else {
          loader.errorHandler(data)
          reject(data)
        }
      })
    })
  }
}

loader.postFile = function(option) {
  if (this.beforeRequest() == null) {
    return uploadFileByElementUI(option, this)
  }
}.bind(loader)

export default loader
